//
//  SocketModel.swift
//  jiaoyi
//
//  Created by wjk on 2018/11/16.
//  Copyright © 2018 wjk. All rights reserved.
//

import UIKit
import SocketIO


class SocketModel: NSObject {
    public static let `default` = SocketModel.init()
    
    var manager:SocketManager?
    
    
    var priceBl:NormalCallback?
    var statusBl:NormalCallback?
    var runtimeBl:NormalCallback?
    
    override init() {
        super.init()
        
        manager?.defaultSocket.on(clientEvent: .connect) {data, ack in
            //            print("socket connected\(self.manager?.defaultSocket.sid ?? "")")
            print("-----初始化socket--->>>")
        }
        manager?.defaultSocket.on(clientEvent: .disconnect) {data, ack in
            //            print("socket disconnect\(self.manager?.defaultSocket.sid)")
        }
        manager?.defaultSocket.on(clientEvent: .error) {data, ack in
            //            print("socket error\(self.manager?.defaultSocket.sid)")
        }
        
        manager?.defaultSocket.on("message_type", callback: { (data, ack) in
            //            showMessage(message: jsonFormater(data: data).description)
        })
        
        manager?.defaultSocket.on("price", callback: {[weak self] (data, ack) in
            
            self?.priceBl?(data, ack)
        })
        manager?.defaultSocket.on("target_status", callback: {[weak self] (data, ack) in
            self?.statusBl?(data, ack)
        })
        manager?.defaultSocket.on("runtime", callback: {[weak self] (data, ack) in
            
            self?.runtimeBl?(data, ack)
        })
        
    }
    
    func connect(_ url:String, _ token: String) -> Void {
        manager?.defaultSocket.disconnect()
        manager?.defaultSocket.removeAllHandlers()
        manager = SocketManager(socketURL: URL(string: url)!, config: [.log(true), .compress, .connectParams(["token":token,"transport":"polling","t":"MQ-tEbI","EIO":"3"]), .path("/ws")])        
        manager?.defaultSocket.connect()
    }
    
}
